package com.alex.tube;

import java.io.File;
import java.io.IOException;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

import org.apache.commons.io.FileUtils;

import com.alex.utils.http.HttpClientFactory;
import com.alex.utils.http.HttpResult;
import com.alex.utils.http.RequestBuilderFactory;

public class ImageDownloader {

	private RequestBuilderFactory rbf;

	private AtomicInteger count = new AtomicInteger(0);

	public void donwload(Set<String> images, final File path) throws Exception {
		HttpClientFactory httpClientFactory = new HttpClientFactory();
		httpClientFactory.setThreadSafe(true);
		rbf = new RequestBuilderFactory(httpClientFactory.create());

		ExecutorService service = Executors.newFixedThreadPool(10);
		
		for (final String image : images) {
			count.incrementAndGet();
			service.execute(new Runnable() {
				@Override
				public void run() {
					try {
						download(image, path);
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			});
		}
		service.awaitTermination(100, TimeUnit.DAYS);
	}

	private void download(String url, File path) throws IOException {
		System.out.println(url + " - " + count.decrementAndGet());

		String name = SecurityUtils.encodeMD5(url);
		String ext = getExtension(url);
		if (ext != null) {
			name += "." + ext;
		}

		File file = new File(path, name.charAt(0) + "/" + name);
		if (file.exists()) {
			return;
		}

		HttpResult httpResult = rbf.get(url).getResult();
		byte[] image = httpResult.getResponseBodyAsByteArray();

		FileUtils.writeByteArrayToFile(file, image);
	}

	private String getExtension(String url) {
		int p = url.lastIndexOf("/");
		if (p < 0) {
			return null;
		}
		url = url.substring(p);
		p = url.lastIndexOf(".");
		if (p < 0) {
			return null;
		}
		return url.substring(p + 1);
	}

}
